import router from './router'
import store from './store'
import storage from 'store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { domTitle, setDocumentTitle } from '@/utils/domUtil'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { i18nRender } from '@/locales'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const loginRoutePath = '/user/login'
const defaultRoutePath = '/'
const whiteList = ['login', 'register', 'registerResult'] // no redirect whitelist
store.dispatch('GenerateRoutes', {}).then(() => {
  // 根据roles权限生成可访问的路由表
  // 动态添加可访问路由表
  router.addRoutes(store.getters.addRouters)
})
router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar

  // 判断是否登录
  if (storage.get(ACCESS_TOKEN)) {
    // 如果是登录路径
    if (to.path === loginRoutePath) {
      next({ path: defaultRoutePath })
      NProgress.done()
    } else {
      // 不是登录页，不做权限控制
      next()
    }
  } else {
    // 是否白名单，白名单跳过
    if (whiteList.includes(to.name)) {
      next()
    } else {
      next({ path: loginRoutePath, query: { redirect: to.fullPath } })
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})
